package com.hospital.tools;


import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.net.Uri;
import android.util.Log;


public class SMSReader{

	private Activity act=null;

	public SMSReader(Activity in){
		act=in;
	}



	public String getSmsAndSendBack()
	{
		String[] projection = new String[] {
				"_id",
				"address",
				"person",
				"body",
				"service_center"
		};
		String str="";


		try{//查询有无新来的未读短信
			Cursor myCursor = act.managedQuery(Uri.parse("content://sms/inbox"),
					projection,
					"read = 0", null , "date desc");
			Log.i("msm", "pro start");
			str=processResults(myCursor, true);

			/**new Handler().postDelayed(new Runnable(){
			@Override
			public void run() {
			// TODO Auto-generated method stub
			Intent intent = new Intent(rec.this,log.class);
			rec.this.startActivity(intent);
			rec.this.finish();
			}
			}, 2000);***/
			// str.append(processResults(myCursor, true));
			// str.append("\n"+"\n"+"谢谢!");

		}
		catch (SQLiteException ex)
		{
		}
		return str;
	}
	/**
	 * 处理短信结果
	 * @param cur
	 * @param all 用来判断是读一条还是全部读。后来没有用all，可以无视
	 */
	private String processResults(Cursor cur, boolean all) {
		String ret="";

		Log.i("count", ""+cur.getCount());
		if (cur.moveToFirst()) {

			String s_id;//信息ID
			String phoneNumber; //信息号码
			String sms;	//信息内容
			String sc;//服务中心

			int id = cur.getColumnIndex("_id");
			int phoneColumn = cur.getColumnIndex("address");
			int smsColumn = cur.getColumnIndex("body");
			int s=cur.getColumnIndex("service_center");
			do {
				// Get the field values
				s_id = cur.getString(id);
				phoneNumber = cur.getString(phoneColumn);
				sms = cur.getString(smsColumn);
				sc=cur.getString(s);
				Log.i("sms", sms+phoneNumber);
				//||phoneNumber.equals("+8615267876093")
				if(phoneNumber.equals("106288190574")||phoneNumber.equals("106583107")||phoneNumber.equals("106593377"))
				{
					Log.i("smsinfo", sms);
					//  ret=sms.split("cb")[1];
					Log.i("retinfo", ret);
					if(sms.contains("回复"))
						ret=sms.substring(sms.lastIndexOf("回复")+2,sms.lastIndexOf("回复")+5);
					else if(sms.contains("欢迎注册"))
						ret=sms.substring(sms.lastIndexOf("验证码：")+4,sms.lastIndexOf("验证码：")+12);
					else if(sms.contains("预约成功"))
						ret=sms;
					if(ret.length()>1)
					{
						ContentValues cv = new ContentValues();   //标记本次服务结束，更改回发短信使其失效
						cv.put("read", "1");
						act.getContentResolver().update(Uri.parse("content://sms/inbox/"+s_id), cv, null, null);
						return phoneNumber+"-"+ret;
					}
					Log.i("sms", phoneNumber+"-"+ret);


				}
				if (null==sms)
					sms="";
			} while (cur.moveToNext());

		}

		Log.i("retsize", ret.length()+"");
		return ret;
	}



}
